package com.example.myapplication8;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.transition.FragmentTransitionSupport;
import androidx.viewpager.widget.ViewPager;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initPager()
    {
        ViewPager viewPager = findViewById(R.id.view_pager);

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new StaticFragment());
        fragments.add(new DynamicFragment());
        fragments.add(new ThridFragment());

        ViewPagerAdapter adapter = new ViewPagerAdapter(
                getSupportFragmentManager(),
                FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);

        adapter.setFragments(fragments);

        viewPager.setAdapter(adapter);
    }

    private void initView()
    {
        initPager();

        //1.获取FragmentManager
        FragmentManager fm = getSupportFragmentManager();
        //2.获取FragmentTransaction
        FragmentTransaction ft = fm.beginTransaction();
        //3.添加Fragment
        DynamicFragment fragment = new DynamicFragment();
        ft.add(R.id.fragment_container, fragment);

        //移除
//        ft.remove(fragment);
        //替换
//        ft.replace(R.id.fragment_container,fragment);
        //显示Fragment
//        ft.show(fragment);
        //隐藏Fragment
//        ft.hide(fragment);

        //4.提交，操作完成后必须提交
        //同一个FragmentTrasnaction只可以提交一次，不可重复操作
        ft.commit();

        //为了避免FragmentTransaction重复使用
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, new DynamicFragment())
                .commit();
    }

    class ViewPagerAdapter extends FragmentPagerAdapter
    {

        private List<Fragment> fragments;

        public void setFragments(List<Fragment> fragments)
        {
            this.fragments = fragments;
        }

        public ViewPagerAdapter(@NonNull FragmentManager fm, int behavior)
        {
            super(fm, behavior);
        }

        @NonNull
        @Override
        public Fragment getItem(int position)
        {
            return fragments.get(position);
        }

        @Override
        public int getCount()
        {
            return null != fragments ? fragments.size() : 0;
        }
    }
}